﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

namespace Microsoft.AspNetCore.App
{
    /// <summary>
    /// 负责执行endpoint
    /// </summary>
    public class EndpointMiddleware : IMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly RouteOptions _routeOptions;

        public EndpointMiddleware(
            RequestDelegate next,
            IOptions<RouteOptions> routeOptions)
        {
            _next = next;
            _routeOptions = routeOptions.Value;
        }

        public async Task Invoke(HttpContext context)
        {
            var endpoint = context.GetEndpoint();
            if (endpoint!=null)
            {
                await endpoint.RequestDelegate(context);
            }
            else
            {
                await _next(context);
            }
        }
    }

    /// <summary>
    /// 注册一个用于执行Endpoint的中间件
    /// </summary>
    public static class EndpointMiddlewareExtensions
    {
        /// <summary>
        /// 映射终结点并且注册一个中间件来执行路由的中间点
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="endpoints"></param>
        public static void UseEndpoints(this IApplicationBuilder builder, Action<IEndpointRouteBuilder> endpoints)
        {
            var endpointRouteBuilder = new EndpointRouteBuilder();
            endpoints(endpointRouteBuilder);
            var routeOptions = builder.ApplicationServices.GetRequiredService<IOptions<RouteOptions>>().Value;
            routeOptions.EndpointDataSource = endpointRouteBuilder.DataSource;
            builder.UseMiddlware<EndpointMiddleware>();
        }
    }
}

